<template>
  <div class="bideliBuying">
    <!-- 个人记录 -->
    <div class="personRecord pointer front-color">
      <div class="my_investment" @click="toBideliRecord('myInvestment', symbol)">
        <div class="iconDiv borderbox"><i class="icon-money fontsize18"></i></div>
        <div class="text">{{$t('myAdd.bideli.myPosition')}}</div>
      </div>
      <div class="income_detail" @click="toBideliRecord('incomeDetail', symbol)">
        <div class="iconDiv borderbox"><i class="icon-bill fontsize18"></i></div>
        <div class="text">{{$t('myAdd.bideli.incomeBreakdown')}}</div>
      </div>
    </div>
    <div class="bideliBuying_cont">
      <div class="product_buy clearfix front-color">
        <div class="product_buy_baseInfo borderbox">
          <div class="rateAndCycle clearfix">
            <div class="percentage">
              <p class="value"><span class="numV">{{configDetailData.scale}}</span><span class="unit">%</span></p>
              <p class="text"><span class="des">{{$t('myAdd.bideli.expectedRateOfReturn')}}</span></p>
            </div>
            <div class="cysle">
              <p class="value"><span class="daysV">{{configDetailData.period}}</span><span class="unit">{{$t('myAdd.bideli.day')}}</span></p>
              <p class="text"><span class="des">{{$t('myAdd.bideli.revenueCycle')}}</span></p>
            </div>
          </div>
          <div class="progress">
            <div class="proress_title fontsize18">{{$t('myAdd.bideli.progressBar')}}</div>
            <div class="progress_bar">
              <div class="start_text fontsize14">
                <span class="start">{{$t('myAdd.bideli.purchase')}}</span><span>{{$t('myAdd.bideli.interestRate')}}</span><span class="end">{{$t('myAdd.bideli.maturity')}}</span>
              </div>
              <div class="show_bar">
                <div class="ing" ref="ing">
                  <div class="ing_bar front-color">
                    <span class="start_point"></span>
                    <span class="center_pointer"></span>
                    <span class="end_pointer"></span>
                    <div class="bar"></div>
                  </div>
                </div>
                <div class="noCarry" ref="noCarry">
                  <div class="ing_bar">
                    <span class="start_point"></span>
                    <span class="center_pointer"></span>
                    <span class="end_pointer"></span>
                    <div class="bar"></div>
                  </div>
                </div>
              </div>
              <div class="start_date fontsize14"><span class="start">{{_P.dateFilter(configDetailData.stime)}}</span><span>{{_P.dateFilter(configDetailData.btime)}}</span><span class="end">{{_P.dateFilter(configDetailData.etime)}}</span></div>
            </div>
          </div>
        </div>
        <div class="product_buy_operate borderbox">
          <div class="prodct_title">
            <h4 class="title">{{configDetailData.name}}</h4>
            <span class="risk">{{$t('myAdd.bideli.riskType')}}：</span><span class="degree">{{configDetailData.risk}}</span>
            <span class="back pointer" @click="goBack">< {{$t('myAdd.bideli.prevPage')}}</span>
          </div>
          <div class="amount clearfix">
            <div class="remaining">
              <p class="text fontsize14">{{$t('myAdd.bideli.totalRemainingDelivery')}}</p>
              <p class="val"><span class="valNum">{{configDetailData.remainingQuantity}}</span><span>{{symbol}}</span></p>
            </div>
          </div>
          <div class="operate clearfix">
            <InlineInput
              :property = "formList.buyNumber"
              v-model="formList.buyNumber.value"
              v-on:onevents="somethings"
            ></InlineInput>
            <button :class="{readOnly: configDetailData.status != 1 || inpErrorInfo }" @click="enterPassW">{{buyBtnText}}</button>
            <span class="purchaseCurrency fontsize18">{{symbol}}</span>
          </div>
          <p class="inpErrorInfo" v-if="inpErrorInfo">{{inpErrorInfo}}</p>
          <div class="limit_time">
            {{$t('myAdd.bideli.availableBalance')}}: {{symbolAccInfo.normal_balance}} {{symbol}}
          </div>
          <div class="income_rule" v-if="configDetailData.rule">
            <p class="fontsize14">{{_P.subStrFn(configDetailData.rule, 0, 160)}}</p>
          </div>
        </div>
      </div>
      <div class="product_info">
        <div class="tab">
          <span class="fontsize24 pointer" :class="{tabActive: activeTab === 'productInfo'}" @click="changeTab('productInfo')">{{$t('myAdd.bideli.productInformation')}}</span>
          <span class="fontsize24 pointer" :class="{tabActive: activeTab === 'commonProblem'}"  @click="changeTab('commonProblem')">{{$t('myAdd.bideli.commonProblem')}}</span>
        </div>
        <div class="tabCont">
          <div class="productInfo" v-show="activeTab === 'productInfo'">
            <div class="list clearfix">
              <div class="productInfo_list list_left">
                <P class="fontsize16" v-for="(item, index) in productInfo1" :key="index"><span class="title">{{item.text}}</span><span class="des">{{item.value}}</span></P>
              </div>
              <div class="productInfo_list">
                <P class="fontsize16" v-for="(item, index) in productInfo2" :key="index"><span class="title">{{item.text}}</span><span class="des">{{item.value}}</span></P>
              </div>
            </div>
            <div class="productDes">
              <h3 class="fontsize20">{{$t('myAdd.bideli.productManual')}}</h3>
              <p class="fontsize14">{{configDetailData.remark}}</p>
            </div>
          </div>
          <div class="common_problem" v-show="activeTab === 'commonProblem'">
            <div class="common_problem_des" v-html="commonProblemDes"></div>
          </div>
        </div>
      </div>
    </div>
    <elDialog
      title= ''
      :flag= 'detailAlert'
      name= 'detailAlert'
      :width='450'
      :dialogClose='closeDialog'>
      <div class="detailTitle" slot="operation">
        {{$t('myAdd.bideli.purchaseDetails')}}
      </div>
      <div class="detailAlertData" slot="content">
        <div class="data">
          <p v-for="(item, index) in buyDetailDataArr" :key="index"><span class="text">{{item.text}}</span><span class="num">{{item.value}}</span></p>
        </div>
      </div>
      <div class="detailAlertFooter" slot="options">
        <button @click="closeDialog" class="cancel">{{$t('myAdd.bideli.completed')}}</button>
      </div>
    </elDialog>
    <exchangePw :passWordAlert = "passWordAlert" @closePassWordAlert="closePassWordAlert" @submitRequest="submitRequest"></exchangePw>
    <span v-if="publicInfo"></span>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import InlineInput from '@/components/common/inlineInput'
  import elDialog from '@/components/common/addCommon/dialog'
  import exchangePw from '@/components/common/addCommon/exchangePw'
  export default {
    name: 'bideliBuy',
    components: { InlineInput, elDialog, exchangePw },
    data () {
      return {
        symbol: null,
        recordId: null, // 购买记录id
        symbolAccInfo: { normal_balance: null },
        formList: {},
        coinList: null,
        inpErrorInfo: null,
        isCanBuy: true,
        secondClick: true,
        detailAlert: false,
        activeTab: 'productInfo',
        totalProgressLeng: '320',
        commonProblemDes: null,
        configDetailData: {
          scale: null, // 收益率
          period: null, // 周期
          stime: null, // 起购时间
          btime: null, // 起息时间
          etime: null, // 到期时间
          name: null, // 产品名称
          remainingQuantity: null, // 剩余数量
          totalQuantity: null, // 可投资总量
          risk: null, // 投资风险
          investmentQuantity: null, // 用户已购买数量
          upper: null, // 认购上限
          lower: null, // 认购下限
          remark: null, // 产品信息
          status: null, // 状态(0关闭 1开启 2售完)
          timeDifference: null, //   时间差(开售时间 - 当前时间)
          currentTime: null, // 当前服务器时间
          rule: null, // 规则
          id: null
        },
        buyDetailData: {
          coin: null,
          buyQuantity: null,
          fee: null,
          period: null,
          time: null
        },
        passWordAlert: false
      }
    },
    created () {
      this.formList = this.formList_obj
    },
    mounted () {
      this.symbol = this.$route.query.symbol
      this.configDetail()
      this.insideNormal()
    },
    computed: {
      ...mapState({
        publicInfo ({baseData}) {
          if (baseData.isReady) {
            this.coinList = baseData._coinList
            return baseData
          } else {
            return false
          }
        }
      }),
      formList_obj () {
        return {
          buyNumber: {
            title: '',
            formType: 'number',
            name: 'buyNumber',
            placeholder: this.buyNumberPlaceholder,
            value: '',
            readOnly: this.buyNumberReadOnly
          }
        }
      },
      // 产品信息
      productInfo1 () {
        let arr = [
          {text: this.Internationalization.productName, value: this.configDetailData.name},
          {text: this.Internationalization.totalAmount, value: this.configDetailData.totalQuantity + ' ' + this.symbol},
          {text: this.Internationalization.revenueCycle, value: this.configDetailData.period},
          {text: this.Internationalization.expectedRateOfReturn, value: this.configDetailData.scale + '%'}
        ]
        return arr
      },
      productInfo2 () {
        let arr = [
          {text: this.Internationalization.purchaseQuantity, value: this.configDetailData.lower},
          {text: this.Internationalization.purchaseLimit, value: this.configDetailData.upper + ' ' + this.symbol},
          {text: this.Internationalization.riskType, value: this.configDetailData.risk}
        ]
        return arr
      },
      buyBtnText () {
        let text = ''
        if (this.configDetailData.status == 1) {
          text = Number(this.configDetailData.investmentQuantity) > 0 ? this.Internationalization.buyAgain : this.Internationalization.buyNow
        } else {
          this.configDetailData.status == 0 && (text = this.Internationalization.over)
          this.configDetailData.status == 2 && (text = this.Internationalization.soldOut)
        }
        return text
      },
      buyNumberPlaceholder () {
        if (this.configDetailData.lower && this.configDetailData.upper && this.symbolAccInfo.normal_balance && this.symbolPrecision) {
          return this.Internationalization.SnatchLimit + this.configDetailData.lower + '-' + this.configDetailData.upper
        } else {
          return ''
        }
      },
      symbolPrecision () {
        if (this.coinList && this.symbol) {
          return this.coinList[this.symbol].showPrecision
        } else {
          return false
        }
      },
      buyNumberReadOnly () {
        if (this.configDetailData.status != null && this.configDetailData.status != 1) {
          return true
        } else {
          return false
        }
      },
      buyDetailDataArr () {
        let arr = [
          {text: this.Internationalization.buyNumber, value: this.buyDetailData.buyQuantity + ' ' + this.buyDetailData.coin},
          {text: this.Internationalization.fee, value: this.buyDetailData.fee},
          {text: this.Internationalization.revenueCycle, value: this.buyDetailData.period},
          {text: this.Internationalization.purchaseTime, value: this.buyDetailData.time}
        ]
        return arr
      },
      Internationalization () {
        return {
          productName: this.$t('myAdd.bideli.productName'), // 产品名称
          totalAmount: this.$t('myAdd.bideli.totalAmount'), // 投放总量
          revenueCycle: this.$t('myAdd.bideli.revenueCycle'), // 收益周期
          expectedRateOfReturn: this.$t('myAdd.bideli.expectedRateOfReturn'), // 预计收益率
          purchaseQuantity: this.$t('myAdd.bideli.purchaseQuantity'), // 起购数量
          purchaseLimit: this.$t('myAdd.bideli.purchaseLimit'), // 购买上限
          riskType: this.$t('myAdd.bideli.riskType'), // 风险类型
          buyAgain: this.$t('myAdd.bideli.buyAgain'), // 再次购买
          buyNow: this.$t('myAdd.bideli.buyNow'), // 立即抢购
          over: this.$t('myAdd.bideli.over'), // 已结束
          soldOut: this.$t('myAdd.bideli.soldOut'), // 已售完
          SnatchLimit: this.$t('myAdd.bideli.SnatchLimit'), // 抢购限量
          buyNumber: this.$t('myAdd.bideli.buyNumber'), // 购买数量
          fee: this.$t('myAdd.bideli.fee'), // 手续费
          purchaseTime: this.$t('myAdd.bideli.purchaseTime'), // 购买时间
          moreThanTotalAmount: this.$t('myAdd.bideli.moreThanTotalAmount'), // 大于剩余总量
          moreThanSubscriptionLimit: this.$t('myAdd.bideli.moreThanSubscriptionLimit'), // 大于认购上限
          lessThanSubscriptionLimit: this.$t('myAdd.bideli.lessThanSubscriptionLimit'), // 小于认购下限
          buySuc: this.$t('myAdd.bideli.buySuc'), // 小于认购下限
          enterNum: this.$t('myAdd.bideli.enterNum') // 小于认购下限
        }
      }
    },
    watch: {
      'formList_obj' (newV) {
        this.formList = newV
      }
    },
    methods: {
      somethings (val) {
        if (val.name === 'buyNumber') {
          this.$nextTick(() => {
            let precision = this.coinList[this.symbol].showPrecision
            this.formList.buyNumber.value = this._P.fixInput(val.value, precision)
            this.determineInpV(this.formList.buyNumber.value)
          })
        }
      },
      closeDialog () {
        this.detailAlert = false
      },
      configDetail () {
        this.axios({
          url: this.$store.state.url.bideli.config_detail,
          headers: {},
          method: 'POST',
          params: {
            configId: this.$route.query.id,
            recordId: this.$route.query.recordId
          }
        }).then(res => {
          if (res.code.toString() === '0') {
            // let timeDifference // 到期时间 - 起购时间
            // let percent
            let data = res.data
            // let ingW, noCarry
            this.configDetailData.scale = this._P.accMul(data.scale, 100)
            this.configDetailData.period = data.period
            this.configDetailData.stime = data.stime
            this.configDetailData.btime = data.btime
            this.configDetailData.etime = data.etime
            this.configDetailData.name = data.name
            this.configDetailData.remainingQuantity = data.remainingQuantity
            this.configDetailData.totalQuantity = data.totalQuantity
            this.configDetailData.risk = data.risk
            this.configDetailData.investmentQuantity = data.investmentQuantity
            this.configDetailData.upper = data.upper
            this.configDetailData.lower = data.lower
            this.configDetailData.remark = data.remark
            this.configDetailData.status = data.status
            this.configDetailData.timeDifference = data.timeDifference
            this.configDetailData.currentTime = data.currentTime
            this.configDetailData.rule = data.rule
            this.configDetailData.id = data.id
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
          /* if (this.configDetailData.timeDifference >= 0) {
            this.$refs.ing.style.width =  '0px'
            this.$refs.noCarry.style.width = this.totalProgressLeng + 'px'
          } else {
            timeDifference = this._P.accSub(this.configDetailData.etime, this.configDetailData.stime)
            console.log(timeDifference)
            percent = this._P.accDiv(Math.abs(this.configDetailData.timeDifference), timeDifference)
            percent = this._P.cutStrTo(percent, 2)
            console.log(percent)
            if (percent >= 1) {
              this.$refs.ing.style.width = this.totalProgressLeng + 'px'
              this.$refs.noCarry.style.width = '0px'
            } else {
              ingW = Math.abs(parseInt(this.totalProgressLeng * percent))
              noCarry = this._P.accSub(this.totalProgressLeng, ingW)
              this.$refs.ing.style.width = ingW + 'px'
              this.$refs.noCarry.style.width = noCarry + 'px'
              console.log(ingW, noCarry)
            }
          } */
        })
      },
      // 币币账户 余额
      insideNormal () {
        this.axios({
          url: this.$store.state.url.fund.account_balance,
          headers: {},
          params: {},
          method: 'post'
        }).then(res => {
          if (res.code.toString() === '0') {
            let data = res.data.allCoinMap
            this.symbolAccInfo.normal_balance = this._P.lastD(this._P.fixD(data[this.symbol].normal_balance, this.symbolPrecision))
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
        })
      },
      // 表单 的 值 做判断
      determineInpV (val) {
        this.isCanBuy = true
        this.inpErrorInfo = null
        // 是否大于 可用 余额
        if (Number(val) > Number(this.symbolAccInfo.normal_balance)) {
          this.inpErrorInfo = this.$t('myAdd.bideli.buyUpTo', {normal_balance: this._P.lastD(this.symbolAccInfo.normal_balance), symbol: this.symbol})
          this.isCanBuy = false
          return false
        }
        // 是否大于 剩余总量
        if (Number(val) > Number(this.configDetailData.remainingQuantity)) {
          this.inpErrorInfo = this.Internationalization.moreThanTotalAmount
          this.isCanBuy = false
          return false
        }
        // 是否超出 大小 限额
        if (Number(val) > Number(this.configDetailData.upper)) {
          this.inpErrorInfo = this.Internationalization.moreThanSubscriptionLimit
          this.isCanBuy = false
          return false
        }
        if (Number(val) < Number(this.configDetailData.lower)) {
          this.inpErrorInfo = this.Internationalization.lessThanSubscriptionLimit
          this.isCanBuy = false
          return false
        }
      },
      // 立即抢购
      buyNow () {
        if (!this.secondClick) {
          return false
        }
        this.secondClick = false
        this.axios({
          url: this.$store.state.url.bideli.investment_buying,
          headers: {},
          params: {
            id: this.configDetailData.id,
            buyQuantity: this.formList.buyNumber.value
          },
          method: 'POST'
        }).then(res => {
          if (res.code.toString() === '0') {
            let data = res.data
            this.buyDetailData.buyQuantity = data.buyQuantity
            this.buyDetailData.coin = data.coin
            this.buyDetailData.fee = data.fee
            this.buyDetailData.period = data.period
            this.buyDetailData.time = this._P.formatTime(data.time)
            this.detailAlert = true
            this.$store.dispatch('setTipState', {text: this.Internationalization.buySuc})
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
          this.secondClick = true
        })
      },
      // 选项卡切换
      changeTab (tab) {
        this.activeTab = tab
        tab === 'commonProblem' && !this.commonProblemDes && this.getCommonProblem()
      },
      // 常见问题
      getCommonProblem () {
        this.axios({
          url: this.$store.state.url.bideli.common_problem,
          method: 'POST',
          params: {},
          headers: {}
        }).then(res => {
          if (res.code.toString() === '0') {
            this.commonProblemDes = res.data
          } else {
            this.$store.dispatch('setTipState', {text: res.msg, type: 'error'})
          }
        })
      },
      // 返回上一页
      goBack () {
        this.$router.go(-1)
      },
      // 去投资 记录 页
      toBideliRecord (tab, symbol) {
        this.$router.push({
          path: '/bideliRecord',
          query: {
            tab: tab,
            symbol: symbol
          }
        })
      },
      // 打开交易密码弹窗
      enterPassW () {
        if (this.configDetailData.status === 0 || this.configDetailData.status === 2) {
          return false
        }
        if (!this.formList.buyNumber.value) {
          this.inpErrorInfo = this.Internationalization.enterNum
          this.isCanBuy = false
          return false
        }
        if (this.inpErrorInfo) {
          return false
        }
        this.passWordAlert = true
      },
      // 关闭交易密码弹窗
      closePassWordAlert () {
        this.passWordAlert = false
      },
      // 输入完交易密码触发这个函数
      submitRequest () {
        this.buyNow()
      }
    }
  }
</script>

